/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.settings;

import com.intellij.ide.startup.StartupActionScriptManager;
import com.intellij.lang.ant.config.AntBuildFile;
import com.intellij.lang.ant.config.AntBuildListener;
import com.intellij.lang.ant.config.AntBuildTarget;
import com.intellij.lang.ant.config.AntConfiguration;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileAdapter;
import com.intellij.openapi.vfs.VirtualFileEvent;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileManagerListener;
import com.intellij.openapi.vfs.VirtualFileMoveEvent;
import com.intellij.openapi.vfs.ex.VirtualFileManagerEx;
import com.intellij.util.io.ZipUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarOutputStream;

public class SettingsChecker implements ProjectComponent {
    private static final String CONFIG_INTELLIJ_PLUGINS = "/config/intellij/plugins";
    private static final String CONFIG_INTELLIJ = "/config/intellij";
    boolean refreshing = false;
    boolean settingsChanged = false;
    boolean pluginsChanged = false;
    boolean workspaceChanged = false;
    private Logger logger = Logger.getInstance(getClass().getName());
    private long manualChange = 0;
    private boolean updateInProgress = false;
    private VirtualFileAdapter virtualfilelistener;
    private VirtualFileManagerListener virtualfilemanagerlistener;
    private Project project;
    private VirtualFile settingsVirtualFile;

    public SettingsChecker(Project project) {
        logger.info("settingschecker");
        this.project = project;
    }

    public void settingsChanged(boolean updateSettings, boolean updatePlugins, boolean updateWorkspace) {
        try {
            File intellijPlugins = new File(PathManager.getConfigPath(), "intellij-plugins.zip");
            if (intellijPlugins.exists()) {
                logger.info("Purging " + intellijPlugins);
                intellijPlugins.delete();
            }
            if (updateSettings) {
                File source = new File(getSettingsFile());
                File destination = new File(PathManager.getConfigPath());
                StartupActionScriptManager.UnzipCommand unzipcommand =
                        new StartupActionScriptManager.UnzipCommand(source, destination);
                StartupActionScriptManager.addActionCommand(unzipcommand);
            }
            if (updatePlugins) {
                File pluginsDir = new File(PathManager.getPluginsPath());
                File ourPluginsDir = new File(getPluginsDirectory());
                File exportFile = new File(PathManagerEx.getPluginTempPath(), "plugins.jar");
                JarOutputStream jaroutputstream = new JarOutputStream(new BufferedOutputStream(
                        new FileOutputStream(exportFile)));
                Set addedFiles = new HashSet();
                FileFilter fileFilter = new FileFilter() {
                    public boolean accept(File file) {
                        return !file.getName().equals("CVS") && !file.getName().equals(".svn");
                    }
                };
                ZipUtil.addDirToZipRecursively(jaroutputstream, exportFile, ourPluginsDir, "", fileFilter, addedFiles);
                jaroutputstream.close();
                StartupActionScriptManager.DeleteCommand deletePluginscommand =
                        new StartupActionScriptManager.DeleteCommand(pluginsDir);
                StartupActionScriptManager.UnzipCommand unzipcommand =
                        new StartupActionScriptManager.UnzipCommand(exportFile, pluginsDir, null);
                StartupActionScriptManager.DeleteCommand deleteTempFileCommand =
                        new StartupActionScriptManager.DeleteCommand(exportFile);
                StartupActionScriptManager.addActionCommand(deletePluginscommand);
                StartupActionScriptManager.addActionCommand(unzipcommand);
                StartupActionScriptManager.addActionCommand(deleteTempFileCommand);
            }
            if (updateWorkspace) {
                AntConfiguration antConfiguration = AntConfiguration.getInstance(project);
                AntBuildFile[] antBuildFiles = antConfiguration.getBuildFiles();
                for (int i = 0; i < antBuildFiles.length; i++) {
                    AntBuildFile antBuildFile = antBuildFiles[i];
                    logger.info("AntBuildFile: " + antBuildFile);
                    AntBuildTarget buildTarget = antBuildFile.getModel().findTarget("load-workspace");
                    logger.info("Build target = " + buildTarget);
                    if (buildTarget != null) {
                        buildTarget.run(new DataContext() {
                            @Nullable
                            public Object getData(@NonNls String dataId) {
                                logger.info("getData(" + dataId + ")");
                                return null;
                            }
                        }, new AntBuildListener() {
                            public void buildFinished(int state, int errorCount) {
                                logger.info("buildFinished(" + state + "," + errorCount + ")");
                            }
                        });
                    }
                }
            }
            if (updateSettings || updatePlugins) {
                String changedItems = getChangedItemsString(updateSettings, updatePlugins, updateWorkspace);
                String message = changedItems + " have changed.  You need to restart to activate the new items.  Shutdown IDEA now?";
                int result = Messages.showOkCancelDialog(message, changedItems + " have changed", Messages.getQuestionIcon());
                if (result == 0) {
                    ApplicationManager.getApplication().exit();
                }
            } else {
                Messages.showInfoMessage("Workspace has changed and has been reloaded", "Workspace has changed");
            }
        } catch (IOException e) {
            Messages.showErrorDialog("Error reading settings file or plugins: " + e.getMessage(), "Error Reading Settings");
        }
    }

    public String getComponentName() {
        return "SettingsListener";
    }

    public void initComponent() {
        logger.info("initComponent");
    }

    public void disposeComponent() {
        logger.info("disposeComponent");
    }

    public void projectOpened() {
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
            public void run() {
                settingsVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(getSettingsFile()));
                setUpListeners();
                ((VirtualFileManagerEx) VirtualFileManagerEx.getInstance()).addVirtualFileManagerListener(virtualfilemanagerlistener);
                VirtualFileManager.getInstance().addVirtualFileListener(virtualfilelistener);
            }
        });
    }

    public void projectClosed() {
        ((VirtualFileManagerEx) VirtualFileManagerEx.getInstance()).removeVirtualFileManagerListener(virtualfilemanagerlistener);
        VirtualFileManager.getInstance().removeVirtualFileListener(virtualfilelistener);
    }

    public String getSettingsFile() {
        return getConfigDirectory() + File.separatorChar + "settings.jar";
    }

    public String getConfigDirectory() {
        return getProjectPath() + File.separatorChar + "config" + File.separatorChar + "intellij";
    }

    public void manualChange() {
        manualChange = System.currentTimeMillis() + 10000;
    }

    public String getPluginsDirectory() {
        return getConfigDirectory() + File.separatorChar + "plugins";
    }

    public void updateInProgress(boolean updateInProgress) {
        if (updateInProgress) {
            this.updateInProgress = true;
            logger.info("Update in progress");
        } else {
            this.updateInProgress = false;
            logger.info("Update completed");
            checkForChanges();
        }
    }

    private String getChangedItemsString(boolean updateSettings, boolean updatePlugins, boolean updateWorkspace) {
        List changed = new ArrayList();
        if (updateSettings) {
            changed.add("Settings");
        }
        if (updatePlugins) {
            changed.add("Plugins");
        }
        if (updateWorkspace) {
            changed.add("Workspace");
        }
        return prettyPrintString(changed);
    }

    private String prettyPrintString(List changed) {
        StringBuffer sb = new StringBuffer();
        int pos = 0;
        while (true) {
            String s = (String) changed.get(pos++);
            sb.append(s);
            if (pos == changed.size()) {
                break;
            }
            if (pos == changed.size() - 1) {
                sb.append(" and ");
            } else {
                sb.append(", ");
            }
        }
        String changedItems = sb.toString();
        return changedItems;
    }

    private void setUpListeners() {
        virtualfilemanagerlistener = new VirtualFileManagerListener() {

            public void beforeRefreshStart(boolean b) {
                refreshing = true;
                //settingsChanged = false;
                //pluginsChanged = false;
            }

            public void afterRefreshFinish(boolean b) {
                refreshing = false;
                checkForChanges();
            }
        };
        virtualfilelistener = new VirtualFileAdapter() {
            public void fileCreated(VirtualFileEvent virtualFileEvent) {
                processChange(virtualFileEvent);
            }

            public void fileDeleted(VirtualFileEvent virtualFileEvent) {
                processChange(virtualFileEvent);
            }

            public void fileMoved(VirtualFileMoveEvent virtualFileMoveEvent) {
                processChange(virtualFileMoveEvent);
            }

            public void contentsChanged(VirtualFileEvent virtualFileEvent) {
                processChange(virtualFileEvent);
            }
        };
    }

    private void checkForChanges() {
        logger.info("checkingForChanges= updates:" + updateInProgress + " settings:" + settingsChanged + " plugins:" + pluginsChanged + " workspace: " + workspaceChanged);
        if (!updateInProgress && (settingsChanged || pluginsChanged || workspaceChanged)) {
//            if (System.currentTimeMillis() < manualChange) {
//                logger.info("manualChange override");
//            } else {
            final boolean updateSettings = settingsChanged;
            final boolean updatePlugins = pluginsChanged;
            final boolean updateWorkspace = workspaceChanged;
            ApplicationManager.getApplication().invokeLater(new Runnable() {
                public void run() {
                    settingsChanged(updateSettings, updatePlugins, updateWorkspace);
                }
            }, ModalityState.NON_MODAL);
//            }
            settingsChanged = false;
            pluginsChanged = false;
            workspaceChanged = false;
        }
    }

    private void processChange(VirtualFileEvent virtualFileEvent) {
        VirtualFile virtualFile = virtualFileEvent.getFile();
//        logger.info(updateInProgressCounter + ":" + virtualFile.getPath());
        if (updateInProgress && virtualFile.equals(settingsVirtualFile)) {
            logger.info("settings file change detected: " + virtualFile);
            settingsChanged = true;
        } else if (virtualFile.getPath().indexOf(CONFIG_INTELLIJ_PLUGINS) != -1) {
            if (virtualFile.getPath().indexOf("/CVS/") == -1 && virtualFile.getPath().indexOf("/.svn/") == -1 && !virtualFile.isDirectory()) {
                logger.info("plugins file change detected: " + virtualFile);
                pluginsChanged = true;
            }
        } else if (updateInProgress && virtualFile.getPath().indexOf(CONFIG_INTELLIJ) != -1) {
            if (virtualFile.getExtension() != null && virtualFile.getExtension().equals("iws")) {
                logger.info("workspace file change detected: " + virtualFile);
                workspaceChanged = true;
            }
        }
    }

    private String getProjectPath() {
        VirtualFile baseDir = project.getBaseDir();
        if (baseDir.isInLocalFileSystem()) {
            return baseDir.getPath();
        }
        throw new IllegalStateException("Project basedir " + baseDir + " is not local");
    }

    public static SettingsChecker getInstance(Project project) {
        return project.getComponent(SettingsChecker.class);
    }
}


